import React, { useRef, useState } from 'react';
import { Button, message, Form, Input, Radio, Spin, InputNumber, Select } from 'antd';
import { DrawerForm } from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PlusOutlined, FormOutlined } from '@ant-design/icons';
import { add, edit, update } from '@/services/writingAdmin/setting/author/api';
import { getStorage } from '@/services/writingAdmin/setting/config/api';
interface PorpsType {
  onConfirm: () => void;
  id?: number;
}
const FormIndex: React.FC<PorpsType> = (porps) => {
  const restFormRef = useRef<ProFormInstance>();
  const [loading, setLoading] = useState(porps.id ? false : true);
  const [storageData, setStorageData] = useState<any>(null);
  const [storageDataLoading, setStorageDataLoading] = useState<boolean>(false);
  const { TextArea } = Input;
  const formData: API.WritingAdminAuthorForm = {
    id: null,
    name: '',
    name_tr: '',
    death_year: '',
    birth_year: '',
    desc: '',
    desc_tr: '',
    dynasty_id: null,
    dynasty: '',
    dynasty_tr: '',
    baidu_wiki: '',
    works_count: null,
    status: 1,
    sort: 0,
  };
  return (
    <DrawerForm<API.WritingAdminAuthorForm>
      layout="horizontal"
      labelCol={{ span: 3 }}
      wrapperCol={{ span: 20 }}
      formRef={restFormRef}
      initialValues={formData}
      title={porps.id ? '编辑' : '添加'}
      autoFocusFirstInput
      isKeyPressSubmit
      trigger={
        porps.id ? (
          <Button type="primary" size="small">
            <FormOutlined />
            编辑
          </Button>
        ) : (
          <Button type="primary">
            <PlusOutlined />
            添加
          </Button>
        )
      }
      drawerProps={{
        forceRender: true,
        destroyOnClose: true,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            ...defaultDoms,
            <Button
              loading={loading ? false : true}
              key="extra-reset"
              onClick={async () => {
                const id = props.form?.getFieldValue('id');
                if (id) {
                  await setLoading(false);
                  const res = await edit(id);
                  if (res.status === 20000) {
                    restFormRef.current?.setFieldsValue(res.data);
                    await setLoading(true);
                  }
                } else {
                  props.reset();
                }
              }}
            >
              重置
            </Button>,
          ];
        },
      }}
      onFinish={async (values: any) => {
        values.dynasty = null;
        values.dynasty_tr = null;
        if (values.dynasty_id > 0) {
          for (let i = 0; i < storageData?.dynasty_list?.length; i++) {
            if (values.dynasty_id == storageData.dynasty_list[i].id) {
              values.dynasty = storageData.dynasty_list[i].name;
              values.dynasty_tr = storageData.dynasty_list[i].name_tr;
            }
          }
        }
        let res: any = {};
        if (porps.id) {
          res = await update(porps.id, values);
        } else {
          res = await add(values);
        }
        if (res.status === 20000) {
          message.success(res.message);
          porps.onConfirm();
          return true;
        }
        return false;
      }}
      onVisibleChange={async (visible) => {
        if (visible) {
          await setStorageDataLoading(true);
          const resStorage = await getStorage();
          if (resStorage.status === 20000) {
            await setStorageData(resStorage.data);
            await setStorageDataLoading(false);
          }
          if (porps.id) {
            await setLoading(false);
            const res = await edit(porps.id);
            if (res.status === 20000) {
              await restFormRef.current?.setFieldsValue(res.data);
              await setLoading(true);
            }
          }
        }
      }}
    >
      <Spin spinning={loading ? false : true}>
        {loading && (
          <>
            <Form.Item label="姓名" name="name" rules={[{ required: true, message: '请输入姓名' }]}>
              <Input allowClear placeholder="请输入姓名" />
            </Form.Item>

            <Form.Item
              label="姓名繁体"
              name="name_tr"
              rules={[{ required: true, message: '请输入姓名繁体' }]}
            >
              <Input allowClear placeholder="请输入姓名繁体" />
            </Form.Item>

            <Form.Item label="朝代" name="dynasty_id">
              <Select
                allowClear={true}
                showSearch={true}
                filterOption={(input, option: any) => {
                  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }}
                loading={storageDataLoading}
                notFoundContent="暂无可选朝代"
                placeholder="请选择朝代"
              >
                {storageData?.dynasty_list?.map((item: any) => {
                  return (
                    <Select.Option key={item.id} value={item.id}>
                      {item.name}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>

            <Form.Item label="死亡年份" name="death_year">
              <Input allowClear placeholder="请输入死亡年份" />
            </Form.Item>

            <Form.Item label="出生年份" name="birth_year">
              <Input allowClear placeholder="请输入出生年份" />
            </Form.Item>

            <Form.Item label="描述" name="desc">
              <TextArea showCount placeholder="请输入描述" />
            </Form.Item>

            <Form.Item label="描述繁体" name="desc_tr">
              <TextArea showCount placeholder="请输入描述繁体" />
            </Form.Item>

            <Form.Item label="抓取地址" name="baidu_wiki">
              <Input maxLength={100} allowClear placeholder="请输入抓取地址" />
            </Form.Item>

            <Form.Item label="作品数量" name="works_count">
              <Input maxLength={100} allowClear placeholder="请输入作品数量" />
            </Form.Item>

            <Form.Item
              name="status"
              label="状态"
              rules={[{ required: true, message: '请选择状态' }]}
            >
              <Radio.Group name="status">
                <Radio value={0}>禁用</Radio>
                <Radio value={1}>启用</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item label="排序" name="sort" rules={[{ required: true, message: '请输入排序' }]}>
              <InputNumber
                maxLength={11}
                placeholder="请输入排序"
                min={0}
                style={{ width: '100%' }}
              />
            </Form.Item>
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};
export default FormIndex;
